/**
 * 报告管理相关JavaScript功能
 */

class ReportManager {
    constructor() {
        this.reports = [];
        this.templates = [];
        this.currentPage = 1;
        this.pageSize = 10;
        this.totalPages = 1;
        
        this.initializeEventListeners();
    }
    
    /**
     * 初始化事件监听器
     */
    initializeEventListeners() {
        // 监听模态框关闭事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-backdrop')) {
                this.closeModal(e.target.dataset.modalId);
            }
        });
        
        // 监听表单提交事件
        document.addEventListener('submit', (e) => {
            if (e.target.id === 'dailyReportForm') {
                e.preventDefault();
                this.generateDailyReport();
            } else if (e.target.id === 'weeklyReportForm') {
                e.preventDefault();
                this.generateWeeklyReport();
            } else if (e.target.id === 'monthlyReportForm') {
                e.preventDefault();
                this.generateMonthlyReport();
            } else if (e.target.id === 'customReportForm') {
                e.preventDefault();
                this.generateCustomReport();
            }
        });
        
        // 监听筛选器变化
        document.getElementById('reportTypeFilter')?.addEventListener('change', () => {
            this.loadReports(1);
        });
        
        document.getElementById('reportStatusFilter')?.addEventListener('change', () => {
            this.loadReports(1);
        });
    }
    
    /**
     * 显示加载状态
     */
    showLoading(message = '正在处理...') {
        if (window.showLoading) {
            window.showLoading(message);
        }
    }
    
    /**
     * 隐藏加载状态
     */
    hideLoading() {
        if (window.hideLoading) {
            window.hideLoading();
        }
    }
    
    /**
     * 显示提示消息
     */
    showToast(message, type = 'info') {
        if (window.showToast) {
            window.showToast(message, type);
        }
    }
    
    /**
     * 打开模态框
     */
    openModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }
    }
    
    /**
     * 关闭模态框
     */
    closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }
    }
    
    /**
     * 加载AI报告模板
     */
    async loadAITemplates() {
        try {
            const response = await this.apiRequest('/api/reports/ai-templates', 'GET');
            
            if (response.success) {
                this.templates = response.templates;
                this.renderAITemplates();
            } else {
                this.showToast('加载AI模板失败: ' + response.message, 'error');
            }
        } catch (error) {
            console.error('加载AI模板失败:', error);
            this.showToast('加载AI模板失败', 'error');
        }
    }
    
    /**
     * 渲染AI模板
     */
    renderAITemplates() {
        const container = document.getElementById('aiTemplates');
        if (!container) return;
        
        container.innerHTML = '';
        
        this.templates.forEach(template => {
            const templateCard = document.createElement('div');
            templateCard.className = 'border border-gray-200 rounded-lg p-4 hover:shadow-md transition-all cursor-pointer hover:border-blue-300';
            templateCard.onclick = () => this.useTemplate(template);
            
            const badgeColors = {
                'standard': 'bg-blue-100 text-blue-800',
                'comprehensive': 'bg-purple-100 text-purple-800',
                'strategic': 'bg-indigo-100 text-indigo-800',
                'deep': 'bg-red-100 text-red-800',
                'predictive': 'bg-green-100 text-green-800'
            };
            
            const badgeColor = badgeColors[template.config?.ai_analysis_depth] || 'bg-gray-100 text-gray-800';
            
            templateCard.innerHTML = `
                <div class="flex items-center justify-between mb-3">
                    <h4 class="font-semibold text-gray-800 text-lg">${template.name}</h4>
                    <div class="flex items-center space-x-2">
                        <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full font-medium">AI</span>
                        <span class="${badgeColor} text-xs px-2 py-1 rounded-full font-medium">${template.config?.ai_analysis_depth || 'standard'}</span>
                    </div>
                </div>
                <p class="text-gray-600 text-sm mb-4 leading-relaxed">${template.description}</p>
                <div class="flex flex-wrap gap-1 mb-3">
                    ${template.sections.map(section => 
                        `<span class="bg-gray-100 text-gray-700 text-xs px-2 py-1 rounded-full">${this.getSectionText(section)}</span>`
                    ).join('')}
                </div>
                <div class="flex items-center justify-between text-sm text-gray-500">
                    <span><i class="fas fa-file-alt mr-1"></i>${template.report_type}</span>
                    <button class="text-blue-600 hover:text-blue-800 font-medium" onclick="event.stopPropagation(); reportManager.useTemplate('${template.id}')">
                        使用模板 <i class="fas fa-arrow-right ml-1"></i>
                    </button>
                </div>
            `;
            
            container.appendChild(templateCard);
        });
    }
    
    /**
     * 获取章节文本
     */
    getSectionText(section) {
        const sectionMap = {
            'overview': '总体概述',
            'statistics': '数据统计',
            'trends': '趋势分析',
            'comparison': '对比分析',
            'geo_analysis': '地理分析',
            'category_analysis': '分类分析',
            'regional_analysis': '区域分析',
            'key_issues': '重点问题',
            'detailed_analysis': '详细分析',
            'root_cause_analysis': '根因分析',
            'recommendations': '建议措施',
            'strategic_recommendations': '战略建议',
            'historical_analysis': '历史分析',
            'trend_prediction': '趋势预测',
            'risk_assessment': '风险评估',
            'early_warning': '预警提示'
        };
        return sectionMap[section] || section;
    }
    
    /**
     * 使用模板
     */
    useTemplate(template) {
        if (template.report_type === 'custom') {
            this.openModal('customReportModal');
            document.getElementById('customReportTitle').value = template.name.replace('AI', '');
            
            // 设置章节选择
            const checkboxes = document.querySelectorAll('#customReportForm input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = template.sections.includes(checkbox.value);
            });
        } else if (template.report_type === 'daily') {
            this.openModal('dailyReportModal');
        } else if (template.report_type === 'weekly') {
            this.openModal('weeklyReportModal');
        } else if (template.report_type === 'monthly') {
            this.openModal('monthlyReportModal');
        }
    }
    
    /**
     * 加载报告列表
     */
    async loadReports(page = 1) {
        try {
            this.showLoading('正在加载报告列表...');
            
            const reportType = document.getElementById('reportTypeFilter')?.value || '';
            const status = document.getElementById('reportStatusFilter')?.value || '';
            
            let url = `/api/reports/?page=${page}&page_size=${this.pageSize}`;
            if (reportType) url += `&report_type=${reportType}`;
            if (status) url += `&status=${status}`;
            
            const response = await this.apiRequest(url, 'GET');
            
            if (response.success) {
                this.reports = response.items;
                this.currentPage = page;
                this.totalPages = response.total_pages;
                this.renderReports();
                this.renderPagination();
            } else {
                this.showToast('加载报告列表失败: ' + response.message, 'error');
            }
        } catch (error) {
            console.error('加载报告列表失败:', error);
            this.showToast('加载报告列表失败', 'error');
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 渲染报告列表
     */
    renderReports() {
        const tbody = document.getElementById('reportsTableBody');
        if (!tbody) return;
        
        tbody.innerHTML = '';
        
        if (this.reports.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                        <i class="fas fa-inbox text-4xl mb-4 block text-gray-300"></i>
                        <p>暂无报告数据</p>
                    </td>
                </tr>
            `;
            return;
        }
        
        this.reports.forEach(report => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            
            const statusInfo = this.getStatusInfo(report.status);
            const typeInfo = this.getTypeInfo(report.report_type);
            const isAIReport = report.config?.type?.startsWith('ai_');
            
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 h-10 w-10">
                            <div class="h-10 w-10 rounded-full ${typeInfo.color} flex items-center justify-center">
                                <i class="${typeInfo.icon} text-white"></i>
                            </div>
                        </div>
                        <div class="ml-4">
                            <div class="text-sm font-medium text-gray-900 flex items-center">
                                ${report.title}
                                ${isAIReport ? '<span class="ml-2 bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">AI</span>' : ''}
                            </div>
                            <div class="text-sm text-gray-500">
                                创建于 ${new Date(report.created_at).toLocaleString('zh-CN')}
                            </div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${typeInfo.badgeColor}">
                        ${typeInfo.text}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusInfo.color}">
                        ${statusInfo.icon} ${statusInfo.text}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${report.generated_at ? new Date(report.generated_at).toLocaleString('zh-CN') : '-'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex items-center space-x-2">
                        <button onclick="reportManager.viewReport(${report.id})" class="text-blue-600 hover:text-blue-900 transition-colors" title="查看报告">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${report.status === 'completed' ? `
                            <button onclick="reportManager.downloadReport(${report.id})" class="text-green-600 hover:text-green-900 transition-colors" title="下载报告">
                                <i class="fas fa-download"></i>
                            </button>
                        ` : ''}
                        ${report.status === 'generating' ? `
                            <button onclick="reportManager.checkReportStatus(${report.id})" class="text-yellow-600 hover:text-yellow-900 transition-colors" title="刷新状态">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        ` : ''}
                        <button onclick="reportManager.deleteReport(${report.id})" class="text-red-600 hover:text-red-900 transition-colors" title="删除报告">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            `;
            
            tbody.appendChild(row);
        });
    }
    
    /**
     * 获取状态信息
     */
    getStatusInfo(status) {
        const statusMap = {
            'generating': {
                text: '生成中',
                color: 'bg-yellow-100 text-yellow-800',
                icon: '<i class="fas fa-spinner fa-spin mr-1"></i>'
            },
            'completed': {
                text: '已完成',
                color: 'bg-green-100 text-green-800',
                icon: '<i class="fas fa-check-circle mr-1"></i>'
            },
            'failed': {
                text: '失败',
                color: 'bg-red-100 text-red-800',
                icon: '<i class="fas fa-exclamation-circle mr-1"></i>'
            },
            'pending': {
                text: '待生成',
                color: 'bg-gray-100 text-gray-800',
                icon: '<i class="fas fa-clock mr-1"></i>'
            }
        };
        return statusMap[status] || {
            text: status,
            color: 'bg-gray-100 text-gray-800',
            icon: '<i class="fas fa-question-circle mr-1"></i>'
        };
    }
    
    /**
     * 获取类型信息
     */
    getTypeInfo(type) {
        const typeMap = {
            'daily': {
                text: '日报',
                color: 'bg-blue-500',
                badgeColor: 'bg-blue-100 text-blue-800',
                icon: 'fas fa-calendar-day'
            },
            'weekly': {
                text: '周报',
                color: 'bg-purple-500',
                badgeColor: 'bg-purple-100 text-purple-800',
                icon: 'fas fa-calendar-week'
            },
            'monthly': {
                text: '月报',
                color: 'bg-indigo-500',
                badgeColor: 'bg-indigo-100 text-indigo-800',
                icon: 'fas fa-calendar-alt'
            },
            'custom': {
                text: '自定义',
                color: 'bg-green-500',
                badgeColor: 'bg-green-100 text-green-800',
                icon: 'fas fa-file-alt'
            }
        };
        return typeMap[type] || {
            text: type,
            color: 'bg-gray-500',
            badgeColor: 'bg-gray-100 text-gray-800',
            icon: 'fas fa-file'
        };
    }
    
    /**
     * 渲染分页
     */
    renderPagination() {
        const pagination = document.getElementById('pagination');
        if (!pagination) return;
        
        pagination.innerHTML = '';
        
        if (this.totalPages <= 1) return;
        
        const paginationHtml = document.createElement('div');
        paginationHtml.className = 'flex items-center justify-center space-x-1';
        
        // 上一页
        if (this.currentPage > 1) {
            const prevBtn = document.createElement('button');
            prevBtn.className = 'px-3 py-2 text-sm bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors';
            prevBtn.innerHTML = '<i class="fas fa-chevron-left mr-1"></i>上一页';
            prevBtn.onclick = () => this.loadReports(this.currentPage - 1);
            paginationHtml.appendChild(prevBtn);
        }
        
        // 页码
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(this.totalPages, this.currentPage + 2);
        
        if (startPage > 1) {
            const firstBtn = document.createElement('button');
            firstBtn.className = 'px-3 py-2 text-sm bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors';
            firstBtn.textContent = '1';
            firstBtn.onclick = () => this.loadReports(1);
            paginationHtml.appendChild(firstBtn);
            
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'px-3 py-2 text-sm text-gray-500';
                ellipsis.textContent = '...';
                paginationHtml.appendChild(ellipsis);
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-2 text-sm border border-gray-300 rounded-md transition-colors ${
                i === this.currentPage ? 'bg-blue-500 text-white' : 'bg-white hover:bg-gray-50'
            }`;
            pageBtn.textContent = i;
            pageBtn.onclick = () => this.loadReports(i);
            paginationHtml.appendChild(pageBtn);
        }
        
        if (endPage < this.totalPages) {
            if (endPage < this.totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'px-3 py-2 text-sm text-gray-500';
                ellipsis.textContent = '...';
                paginationHtml.appendChild(ellipsis);
            }
            
            const lastBtn = document.createElement('button');
            lastBtn.className = 'px-3 py-2 text-sm bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors';
            lastBtn.textContent = this.totalPages;
            lastBtn.onclick = () => this.loadReports(this.totalPages);
            paginationHtml.appendChild(lastBtn);
        }
        
        // 下一页
        if (this.currentPage < this.totalPages) {
            const nextBtn = document.createElement('button');
            nextBtn.className = 'px-3 py-2 text-sm bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors';
            nextBtn.innerHTML = '下一页<i class="fas fa-chevron-right ml-1"></i>';
            nextBtn.onclick = () => this.loadReports(this.currentPage + 1);
            paginationHtml.appendChild(nextBtn);
        }
        
        pagination.appendChild(paginationHtml);
    }
    
    /**
     * 查看报告
     */
    async viewReport(reportId) {
        try {
            this.showLoading('正在加载报告内容...');
            
            const isAIReport = this.reports.find(r => r.id === reportId)?.config?.type?.startsWith('ai_');
            const url = isAIReport ? `/api/reports/${reportId}/ai-content` : `/api/reports/${reportId}`;
            
            const response = await this.apiRequest(url, 'GET');
            
            if (response.success || response.content) {
                this.showReportDetail(response);
            } else {
                this.showToast('加载报告内容失败', 'error');
            }
        } catch (error) {
            console.error('加载报告内容失败:', error);
            this.showToast('加载报告内容失败', 'error');
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 显示报告详情
     */
    showReportDetail(reportData) {
        const content = document.getElementById('reportDetailContent');
        if (!content) return;
        
        const generatedAt = reportData.generated_at ? new Date(reportData.generated_at).toLocaleString('zh-CN') : '未知';
        
        content.innerHTML = `
            <div class="mb-6 pb-6 border-b border-gray-200">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-2xl font-bold text-gray-800">${reportData.title}</h2>
                    <div class="flex items-center space-x-2">
                        ${reportData.data?.report_type === 'daily' ? '<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">日报</span>' : ''}
                        ${reportData.data?.report_type === 'weekly' ? '<span class="bg-purple-100 text-purple-800 text-xs px-2 py-1 rounded-full">周报</span>' : ''}
                        ${reportData.data?.report_type === 'monthly' ? '<span class="bg-indigo-100 text-indigo-800 text-xs px-2 py-1 rounded-full">月报</span>' : ''}
                        ${reportData.data?.report_type === 'custom' ? '<span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">自定义</span>' : ''}
                    </div>
                </div>
                <div class="flex items-center text-sm text-gray-600 space-x-4">
                    <span><i class="fas fa-calendar mr-1"></i>生成时间: ${generatedAt}</span>
                    ${reportData.data?.statistics?.total_petitions ? `<span><i class="fas fa-chart-bar mr-1"></i>数据量: ${reportData.data.statistics.total_petitions}</span>` : ''}
                </div>
            </div>
            
            ${reportData.status === 'generating' ? `
                <div class="text-center py-8">
                    <i class="fas fa-spinner fa-spin text-4xl text-blue-500 mb-4"></i>
                    <p class="text-gray-600">报告正在生成中，请稍候...</p>
                    <button onclick="reportManager.checkReportStatus(${reportData.report_id})" class="mt-4 bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors">
                        <i class="fas fa-sync-alt mr-2"></i>刷新状态
                    </button>
                </div>
            ` : `
                <div class="prose max-w-none">
                    <div class="whitespace-pre-wrap text-gray-800 leading-relaxed">${reportData.content || '暂无内容'}</div>
                </div>
                
                ${reportData.data ? `
                    <div class="mt-8 p-4 bg-gray-50 rounded-lg">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">报告数据概览</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            ${reportData.data.statistics ? `
                                <div class="bg-white p-4 rounded-lg shadow">
                                    <h4 class="font-medium text-gray-700 mb-2">统计信息</h4>
                                    <div class="text-sm text-gray-600">
                                        ${Object.entries(reportData.data.statistics).map(([key, value]) => 
                                            `<div class="flex justify-between">
                                                <span>${this.getSectionText(key)}:</span>
                                                <span class="font-medium">${value}</span>
                                            </div>`
                                        ).join('')}
                                    </div>
                                </div>
                            ` : ''}
                            ${reportData.data.trends ? `
                                <div class="bg-white p-4 rounded-lg shadow">
                                    <h4 class="font-medium text-gray-700 mb-2">趋势分析</h4>
                                    <div class="text-sm text-gray-600">
                                        趋势数据已分析完成
                                    </div>
                                </div>
                            ` : ''}
                            ${reportData.data.geo_distribution ? `
                                <div class="bg-white p-4 rounded-lg shadow">
                                    <h4 class="font-medium text-gray-700 mb-2">地理分布</h4>
                                    <div class="text-sm text-gray-600">
                                        地理分布数据已分析完成
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                ` : ''}
            `}
        `;
        
        this.openModal('reportDetailModal');
    }
    
    /**
     * 检查报告状态
     */
    async checkReportStatus(reportId) {
        try {
            const response = await this.apiRequest(`/api/reports/${reportId}`, 'GET');
            
            if (response.success) {
                // 更新本地报告数据
                const index = this.reports.findIndex(r => r.id === reportId);
                if (index !== -1) {
                    this.reports[index] = response;
                    this.renderReports();
                }
                
                // 如果正在生成，设置定时检查
                if (response.status === 'generating') {
                    setTimeout(() => this.checkReportStatus(reportId), 5000);
                } else if (response.status === 'completed') {
                    this.showToast('报告生成完成！', 'success');
                    this.viewReport(reportId);
                } else if (response.status === 'failed') {
                    this.showToast('报告生成失败: ' + (response.error_message || '未知错误'), 'error');
                }
            }
        } catch (error) {
            console.error('检查报告状态失败:', error);
        }
    }
    
    /**
     * 下载报告
     */
    async downloadReport(reportId) {
        try {
            this.showLoading('正在准备下载...');
            
            const response = await fetch(`/api/reports/${reportId}/export?format=json`, {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `report_${reportId}_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                this.showToast('报告下载成功', 'success');
            } else {
                this.showToast('下载报告失败', 'error');
            }
        } catch (error) {
            console.error('下载报告失败:', error);
            this.showToast('下载报告失败', 'error');
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 删除报告
     */
    async deleteReport(reportId) {
        if (!confirm('确定要删除这个报告吗？此操作无法撤销。')) {
            return;
        }
        
        try {
            this.showLoading('正在删除报告...');
            
            const response = await this.apiRequest(`/api/reports/${reportId}`, 'DELETE');
            
            if (response.success) {
                this.showToast('报告删除成功', 'success');
                this.loadReports(this.currentPage);
            } else {
                this.showToast('删除报告失败: ' + response.message, 'error');
            }
        } catch (error) {
            console.error('删除报告失败:', error);
            this.showToast('删除报告失败', 'error');
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 生成日报
     */
    async generateDailyReport() {
        const formData = {
            report_date: document.getElementById('dailyReportDate').value
        };
        
        await this.generateReport('/api/reports/generate/daily', formData, 'dailyReportModal', 'AI日报');
    }
    
    /**
     * 生成周报
     */
    async generateWeeklyReport() {
        const formData = {
            week_start: document.getElementById('weeklyReportDate').value
        };
        
        await this.generateReport('/api/reports/generate/weekly', formData, 'weeklyReportModal', 'AI周报');
    }
    
    /**
     * 生成月报
     */
    async generateMonthlyReport() {
        const formData = {
            year: parseInt(document.getElementById('monthlyReportYear').value),
            month: parseInt(document.getElementById('monthlyReportMonth').value)
        };
        
        await this.generateReport('/api/reports/generate/monthly', formData, 'monthlyReportModal', 'AI月报');
    }
    
    /**
     * 生成自定义报告
     */
    async generateCustomReport() {
        const sections = Array.from(document.querySelectorAll('#customReportForm input[type="checkbox"]:checked'))
            .map(cb => cb.value);
        
        const formData = {
            title: document.getElementById('customReportTitle').value,
            start_date: document.getElementById('customReportStartDate').value,
            end_date: document.getElementById('customReportEndDate').value,
            sections: sections
        };
        
        await this.generateReport('/api/reports/generate/custom', formData, 'customReportModal', 'AI自定义报告');
    }
    
    /**
     * 生成报告的通用方法
     */
    async generateReport(url, formData, modalId, reportType) {
        try {
            this.showLoading(`正在生成${reportType}...`);
            
            const response = await this.apiRequest(url, 'POST', formData);
            
            if (response.success) {
                this.showToast(`${reportType}生成任务已启动`, 'success');
                this.closeModal(modalId);
                this.loadReports(1);
                
                // 开始检查生成状态
                setTimeout(() => this.checkReportStatus(response.report_id), 3000);
            } else {
                this.showToast(`生成${reportType}失败: ` + response.message, 'error');
            }
        } catch (error) {
            console.error(`生成${reportType}失败:`, error);
            this.showToast(`生成${reportType}失败`, 'error');
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 发送API请求
     */
    async apiRequest(url, method = 'GET', data = null) {
        const token = localStorage.getItem('auth_token');
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        };
        
        const options = {
            method,
            headers
        };
        
        if (data && (method === 'POST' || method === 'PUT')) {
            options.body = JSON.stringify(data);
        }
        
        const response = await fetch(url, options);
        
        if (response.status === 401) {
            // 未授权，跳转到登录页
            window.location.href = '/web/login';
            return;
        }
        
        const result = await response.json();
        
        if (!response.ok) {
            throw new Error(result.message || '请求失败');
        }
        
        return result;
    }
}

// 创建全局实例
window.reportManager = new ReportManager();